package com.startx.core.netty.response.http;

import java.io.UnsupportedEncodingException;

import com.startx.core.system.constants.Headers;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * http短连接数据返回
 */
public class ResourceResponse {

	
	/**
	 * 不返回数据
	 * @param ctx
	 * @param status
	 * @param data
	 */
	public static FullHttpResponse getResponse( HttpResponseStatus status,HttpHeaders... headers) {
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
		setPublicHeader(response, headers);
		return response;
	}
	
	/**
	 * 返回字节数组
	 * @param ctx
	 * @param status
	 * @param data
	 */
	public static FullHttpResponse getResponse( HttpResponseStatus status, byte[] data,
			HttpHeaders... headers) {
		ByteBuf buffer = Unpooled.wrappedBuffer(data);
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);
		setPublicHeader(response, headers);
		return response;
	}

	/**
	 * 返回字符串
	 * @param ctx
	 * @param status
	 * @param result
	 */
	public static FullHttpResponse getResponse(HttpResponseStatus status, String result,
			HttpHeaders... headers) throws UnsupportedEncodingException {
		ByteBuf buffer = Unpooled.wrappedBuffer(result.getBytes("utf-8"));
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);
		setPublicHeader(response, headers);
		return response;
	}

	/**
	 * 设置公共header
	 * 
	 * @param res
	 */
	private static void setPublicHeader(FullHttpResponse res, HttpHeaders... headers) {
		res.headers().add(Headers.getResourceHeader());
		for (HttpHeaders header : headers) {
			res.headers().add(header);
		}
	}
}
